//
//  ExtUITextField.swift
//  koolcar
//
//  Created by huangweiqiang on 2022/6/21.
//

import UIKit

var tf_value_key: UnsafePointer<String>? = nil

extension UITextField {
    func addObserverEditingChangedBlock(aBlock: @escaping (String)->Void) {
        let tempBlock = objc_getAssociatedObject(self, &tf_value_key)
        if tempBlock == nil {
            objc_setAssociatedObject(self, &tf_value_key, aBlock, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        self.addTarget(self, action: #selector(self.editingChangedAction(tf:)), for: .editingChanged)
    }
    
    @objc fileprivate func editingChangedAction(tf: UITextField){
        let tempBlock = objc_getAssociatedObject(self, &tf_value_key) as? (String)->Void
        if tempBlock != nil {
            tempBlock?(tf.text ?? "")
        }
    }
    
    public func setExtPlaceHolder(placeHolder: String, aColor: UIColor, font: UIFont? = nil) {
        let attr = NSMutableAttributedString.init(string: placeHolder)
        attr.addAttributes([NSAttributedString.Key.foregroundColor : aColor], range: NSRange.init(location: 0, length: placeHolder.count))
        if font != nil {
            attr.addAttributes([NSAttributedStringKey.font: font!], range: NSRange.init(location: 0, length: placeHolder.count))
        }
        self.attributedPlaceholder = attr
    }
    
    public func setClearButton(imgName: String) {
        let btn = self.value(forKey: "_clearButton") as? UIButton
        btn?.setImage(UIImage.init(named: imgName), for: .normal)
        btn?.setImage(UIImage.init(named: imgName), for: .highlighted)
    }
}
